<template>
	<view class="search-container">
		<searchBox v-model="s" @confirm="query" @clear="s=''"></searchBox>
		
		<!-- 历史记录 -->
		<view class="history-box">
			<view class="top">
				<text>历史搜索</text>
				<icon type="clear" size="15" @tap="historyList = []"></icon>
			</view>
			<view class="bottom">
				<view class="item" v-for="(item, index) in historyList" :key = "index">{{item}}</view>
			</view> 
		</view>
	</view>
</template>

<script>
	import searchBox from '../../components/searchBox.vue'
	
	export default {
		data() {
			return {
				s:'',  /* 查询的关键字 */
				historyList:[]	/* 搜索历史数组 */
			}
		},
		
		onLoad() {
			this.historyList = uni.getStorageSync('history') || []
		},
		
		watch:{
			historyList(){
				uni.setStorageSync('history', this.historyList)
			}  
		},
		
		// 组件
		components:{
			searchBox
		},
		
		methods: {
			query(){
				// 非空
				if(!this.s){
					return 
				}
				// 不为空 去重
				this.historyList.push(this.s)
				// 去重
				this.historyList = [...new Set(this.historyList)]
				// 长度判断
				if(this.historyList.length > 5){
					this.historyList.shift()
				}
			}
		}
	}
</script>
 
<style lang="less">
	.search-container {
		
		.history-box{
			.top{
				display: flex;
				justify-content: space-between;
				padding: 10rpx;
				margin-bottom: 15rpx;
				margin-top: 15rpx;
			}
			.bottom {
				display: flex;
				flex-wrap: wrap;	/* 让弹性盒元素在必要的时候拆行*/
				.item {
					background-color: #dddddd;
					margin-left: 10rpx;
					margin-right: 10rpx;
					margin-top: 10rpx;
					padding: 15rpx;
				}
			}
		}
	}
</style>
